import datetime
from sanic import Sanic
from sanic.response import text, json
import time
from bs4 import BeautifulSoup
import requests
from loguru import logger
from threading import Thread
from PIL import Image
from io import BytesIO
from fake_useragent import UserAgent
import threading

app = Sanic("wechat")

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36',
    'Referer': 'https://mp.weixin.qq.com/'
}


class showpng(Thread):
    def __init__(self, data, pic):
        Thread.__init__(self)
        self.data = data
        self.pic = pic

    def run(self):
        img = Image.open(BytesIO(self.data))
        # img.show()
        img.save(self.pic)


def addCookie(cookie, token, title, random_user_agent):
    url = "https://zoss.cc/api/biz-readhelper/wx/portal/addCookie"
    params = {
        "cookie": cookie,
        "token": token,
        "name": title,
        "userAgent": random_user_agent
    }

    headers.update({"Content-Type": "application/json"})
    # pprint(self.headers)
    response = requests.post(url, headers=headers, json=params)
    # pprint(response)
    if response.status_code == 200:
        res_json = response.json()
        if res_json['code'] == 200:
            logger.info("新增成功")


def _format(string: str) -> str:
    """去除字符串中不必要的成分并返回

    Args:
        string (str): 要整理的字符串

    Returns:
        str: 处理后的字符串
    """
    text_to_replace = ("\xa0", "\u2002""\u3000")
    string = string.strip()
    for text in text_to_replace:
        string = string.replace(text, "")
    return string


@app.get("/login")
async def login(request):
    session = requests.session()
    session.get('https://mp.weixin.qq.com/', headers=headers)
    session.post('https://mp.weixin.qq.com/cgi-bin/bizlogin?action=startlogin',
                 data='userlang=zh_CN&redirect_url=&login_type=3&sessionid={}&token=&lang=zh_CN&f=json&ajax=1'.format(
                     int(time.time() * 1000)), headers=headers)
    qrcode = 'https://mp.weixin.qq.com/cgi-bin/scanloginqrcode?action=getqrcode&random={}'.format(
        int(time.time() * 1000))
    loginurl = session.get(qrcode)
    dateurl = 'https://mp.weixin.qq.com/cgi-bin/scanloginqrcode?action=ask&token=&lang=zh_CN&f=json&ajax=1'

    current_time = datetime.datetime.now()
    formatted_time = current_time.strftime("%Y%m%d%H%M%S")
    pic = "qrcode/" + formatted_time + ".png"

    t = showpng(loginurl.content, pic)
    t.start()
    cookie_str = ""
    threading.Thread(target=isLogin, args=(session, dateurl,)).start()
    return json({"code": 200, "data": "http://wechat.jsxcloud.com/" + formatted_time + ".png", "message": "success"})


def isLogin(session, dateurl):
    while 1:
        date = session.get(dateurl).json()
        if date['status'] == 0:
            print('二维码未失效，请扫码！')
        elif date['status'] == 6:
            print('已扫码，请确认！')
        if date['status'] == 1:
            print('已确认，登录成功！')
            url = session.post('https://mp.weixin.qq.com/cgi-bin/bizlogin?action=login',
                               data='userlang=zh_CN&redirect_url=&cookie_forbidden=0&cookie_cleaned=1&plugin_used=0&login_type=3&token=&lang=zh_CN&f=json&ajax=1',
                               headers=headers).json()
            # pprint(url)
            res = session.get('https://mp.weixin.qq.com{}'.format(url['redirect_url']), headers=headers)
            # pprint(res.cookies)
            cookiejar = res.cookies
            # pprint(cookiejar)
            cookies_dict = requests.utils.dict_from_cookiejar(cookiejar)

            key_value_pairs = [f"{k}={v}" for k, v in cookies_dict.items()]
            cookie_str = ";".join(key_value_pairs)
            red_url = url['redirect_url']
            token = red_url[red_url.rfind("=") + 1:len(red_url)]

            # 获取公众号名称
            bs = BeautifulSoup(_format(res.text), "html.parser")
            title = _format(bs.find("div", class_="weui-desktop_name").text)

            ua = UserAgent()
            random_user_agent = ua.random

            logger.info("title:{}".format(title))
            logger.info("cookie:{}".format(cookie_str))
            logger.info("token:{}".format(token))
            logger.info("random_user_agent:{}".format(random_user_agent))

            result = {'title': title, 'cookie': cookie_str, 'token': token, 'random_user_agent': random_user_agent}

            addCookie(cookie_str, token, title, random_user_agent)
            return json({"code": 200, "data": result, "mgs": "success"})
            break
        time.sleep(2)


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=10080, workers=8, access_log=False)
